package com.food.user.service.impl;


import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.food.user.dto.CartReturnDto;
import com.food.user.dto.UserCartDto;
import com.food.user.entity.FoodInfo;
import com.food.user.entity.StoreInfo;
import com.food.user.form.AddCartForm;
import com.food.user.form.UpdateCartCountForm;
import com.food.user.mapper.FoodInfoMapper;
import com.food.user.service.CartService;
import com.food.user.service.FoodInfoService;
import com.food.user.service.StoreInfoService;
import com.food.user.util.RedisKeyUtil;
import com.food.user.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private FoodInfoMapper foodInfoMapper;

    @Autowired
    private FoodInfoService foodInfoService;
    @Autowired
    private StoreInfoService storeInfoService;
    @Autowired
    private RedisUtil redisUtil;
    private Snowflake sf= new Snowflake();
    @Override
    public void add(AddCartForm form, Integer userId) throws Exception{

        StoreInfo storeInfo = storeInfoService.getOne(new QueryWrapper<StoreInfo>().eq("store_info_name",form.getStoreInfoName()));
        if (storeInfo==null){
            throw new Exception("违规操作");
        }
        FoodInfo foodInfo = foodInfoService.getById(form.getFoodInfoId());
        if (foodInfo==null){
            throw new Exception("该食品不存在");
        }
        if (foodInfo.getFoodInfoStoreId()!=storeInfo.getStoreInfoId()){
            throw new Exception("违规操作");
        }
        if (!foodInfo.getFoodInfoFoodName().equals(form.getFoodInfoFoodName())){
            throw new Exception("违规操作");
        }

        //查询redis里面是否存在
        String userRedisKey = RedisKeyUtil.userCartKey(userId);
        Set set = redisUtil.sMembers(userRedisKey);
        boolean isExist = false;
        //如果redis里面存在则计数加1
        if(set!=null&&set.size()>0) {
            for (Object snowId : set) {
                Map entries = redisUtil.entries((String) snowId);
                if (entries != null && entries.size() > 0) {
                    String foodInfoId = Long.toString(Long.parseLong((String) entries.get("foodInfoId")));
                    if (foodInfoId != null && foodInfoId.equals(Long.toString(form.getFoodInfoId()))) {
                        redisUtil.hIncrBy((String) snowId, "count", form.getCount());
                        isExist = true;
                        break;
                    }
                }

            }
        }
        //不存在则新增
        if (!isExist) {
            String snowId = RedisKeyUtil.cartInfoKey(sf.nextId()+"");
            redisUtil.sAdd(userRedisKey, snowId);
            HashMap<String, Object> foodMap = new HashMap<>();
            foodMap.put("foodInfoId", Long.toString(form.getFoodInfoId()));
            foodMap.put("storeInfoName", form.getStoreInfoName());
            foodMap.put("foodInfoFoodName", form.getFoodInfoFoodName());
            foodMap.put("foodInfoPrice", form.getFoodInfoPrice());
            foodMap.put("foodInfoCoverPhoto",form.getFoodInfoCoverPhoto());
            foodMap.put("count", Long.toString(form.getCount()));
            redisUtil.putAll(snowId, foodMap);
        }


    }
    @Override
    public boolean delete(Long foodInfoId,Integer userId) throws Exception {
        String userRedisKey = RedisKeyUtil.userCartKey(userId);
        Set set = redisUtil.sMembers(userRedisKey);
        if (set!=null && set.size()>0) {
            for (Object snowId : set) {
                Map<Object, Object> entries = redisUtil.entries((String) snowId);
                if (entries != null && entries.size() > 0 && entries.get("foodInfoId").equals(foodInfoId+"")) {
                    redisUtil.sRem(userRedisKey, (String)snowId);
                    redisUtil.delete((String) snowId);
                    return true;
                }
            }
        }
        return false;
    }
    @Override
    public void update(UpdateCartCountForm form, Integer userId) throws Exception {
        FoodInfo byId = foodInfoService.getById(form.getFoodInfoId());
        if (byId==null){
            throw new Exception("该菜品不存在");
        }
        String userRedisKey = RedisKeyUtil.userCartKey(userId);
        Set set = redisUtil.sMembers(userRedisKey);
        if (set!=null && set.size()>0) {
            for (Object snowId : set) {
                Map<Object, Object> entries = redisUtil.entries((String) snowId);
                if (entries != null && entries.size() > 0 && entries.get("foodInfoId").equals(form.getFoodInfoId())) {
//                    Double count = Double.valueOf((String) redisUtil.hGet((String) snowId, "count"));
//                    Double num=form.getNum().doubleValue();
//                    if (num < 0 && count == 0 - num) {
//                        redisUtil.sRem(String.valueOf(userId), (String)snowId);
//                        redisUtil.delete((String) snowId);
//                    }
//                    redisUtil.hIncrBy((String) snowId, "count", num);


                    redisUtil.put(snowId.toString(),"count",form.getNum()+"");
                }
            }
        }
    }

    @Override
    public List<CartReturnDto> showMyCart(Integer userId) throws Exception {
        String userRedisKey = RedisKeyUtil.userCartKey(userId);
        Set set = redisUtil.sMembers(userRedisKey);
        ArrayList<UserCartDto> userCartDTOS = new ArrayList<UserCartDto>();
        for (Object snowId : set) {
            Map<Object, Object> map = redisUtil.entries(snowId.toString());
            if (map == null || map.size() == 0) {
                continue;
            }
            Long foodInfoId = Long.parseLong((String) map.get("foodInfoId"));
            String storeInfoName = (String) map.get("storeInfoName");
            String foodInfoFoodName = (String)map.get("foodInfoFoodName");
            String foodInfoPrice = (String)map.get("foodInfoPrice");
            String foodInfoCoverPhoto = (String) map.get("foodInfoCoverPhoto");
            Long count = Long.parseLong((String) map.get("count"));
            //计算总价
            Double foodPrice = new Double(foodInfoPrice);
            Double num = new Double(count);
            Double allPrice=foodPrice*num;
            //封装购物车dto
            UserCartDto userCartDto = new UserCartDto();
            userCartDto.setFoodInfoId(foodInfoId);
            userCartDto.setFoodInfoFoodName(foodInfoFoodName);
            userCartDto.setStoreInfoName(storeInfoName);
            userCartDto.setFoodInfoPrice(foodInfoPrice);
            userCartDto.setFoodInfoCoverPhoto(foodInfoCoverPhoto);
            userCartDto.setCount(count);
            userCartDto.setAllPrice(allPrice);
            userCartDto.setKey(snowId.toString());
            userCartDTOS.add(userCartDto);
        }

        //按名称分类
        List<CartReturnDto> returnDtos=new ArrayList<>();
        //存放不重复的店铺名称
        Set<String> NameSet = new HashSet<>();
        for (int i = 0; i < userCartDTOS.size(); i++) {
            //获取当前遍历到的元素
            UserCartDto temp = userCartDTOS.get(i);
            NameSet.add(temp.getStoreInfoName());
//            //将当前遍历到的元素与List集合中的其他元素进行比较
//            for (int j = i + 1; j < userCartDTOS.size(); j++) {
//                //如果有相同的元素，则将其取出来
//                if (temp.getStoreInfoName().equals(userCartDTOS.get(j).getStoreInfoName())) {
//                    NameSet.add(temp.getStoreInfoName());
//                }
//            }
        }
        //封装
        for (String s : NameSet) {
            CartReturnDto cartReturnDto = new CartReturnDto();
            cartReturnDto.setStoreInfoName(s);
            for (UserCartDto userCartDTO : userCartDTOS) {
                if (userCartDTO.getStoreInfoName().equals(s)){
                    cartReturnDto.getUserCartDtos().add(userCartDTO);
                }
            }
            returnDtos.add(cartReturnDto);
        }
        return returnDtos;
    }
}
